package com.ht.managermentserver.security;

import com.ht.managermentserver.sysenum.ErrorCode;
import com.ht.managermentserver.utils.JSONUtil;
import com.ht.managermentserver.utils.JsonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author czy
 * @package com.ht.managermentserver.security
 * @date 2020/6/1 9:00
 */
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

  @Override
  public void handle(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final AccessDeniedException accessDeniedException)
      throws IOException, ServletException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    final String reason = "统一处理，原因：" + accessDeniedException.getMessage();
    response.getWriter().write(JSONUtil.toJsonString(JsonResult.create(reason, ErrorCode.NOLOGIN)));
  }
}
